package com.zp.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zp.api.ApiResult;
import com.zp.util.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.util.StringUtils;

import java.util.HashMap;

/**
 * @author zp
 * @description
 * @created 2021/12/1 16:16
 */

public class ConfigClientService implements EnvironmentAware {

    private StandardEnvironment environment;

    @Autowired
    private ClientConfiguration clientConfiguration;

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = (StandardEnvironment) environment;
    }

    public ApiResult getConfig(){
        String applicationName = environment.getProperty("spring.application.name");
        if (StringUtils.isEmpty(applicationName)) {
            return null;
        }
        String result = null;
        try {
            result = HttpUtil.get(clientConfiguration.getServerConfigUrl() + "/config/getConfig?dataId="+applicationName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        ApiResult apiResult = JSON.toJavaObject(JSON.parseObject(result), ApiResult.class);
        return apiResult;
    }

    public ApiResult checkConfig(){
        String applicationName = environment.getProperty("spring.application.name");
        if (StringUtils.isEmpty(applicationName)) {
            return null;
        }
        String result = null;
        try {
            result = HttpUtil.get(clientConfiguration.getServerConfigUrl() + "/config/checkConfig?dataId="+applicationName+"&md5="+ConfigMd5.getMd5());
        } catch (Exception e) {
            e.printStackTrace();
        }

        ApiResult apiResult = JSON.toJavaObject(JSON.parseObject(result), ApiResult.class);
        return apiResult;
    }
}
